package com.tedu.jdbc.controller;


import com.tedu.jdbc.util.DBUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * @author blue sky
 * @version 1.0
 * @description TODO
 * @date 2023/4/28 22:29
 */

@Slf4j
@Controller
public class UserController {

    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        log.info("处理注册请求");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");

        //判断当前注册信息是否合法(不为空)
        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty() ||
                nickname == null || nickname.isEmpty() ||
                ageStr == null || ageStr.isEmpty()
        ) {
            try {
                log.error("当前注册信息为空");
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        //获取数据库连接
        try (Connection connection = DBUtil.getConnection()) {
            String querySQL = "SELECT username " +
                    "FROM user_info WHERE username = ?";
            PreparedStatement queryPS = connection.prepareStatement(querySQL);
            queryPS.setString(1, username);

            ResultSet resultSet = queryPS.executeQuery();

            //如果注册过就让他重新注册
            if (resultSet.next()) {
                log.error("您已经注册过,请登录");
                response.sendRedirect("/have_user.html");
                return;
            }

            //注册,向表中插入一条用户信息
            String insertSQL = "INSERT INTO user_info (username, `password`, nickname, age) " +
                    "VALUES (?, ?, ?, ?)";
            PreparedStatement insertPS = connection.prepareStatement(insertSQL);
            insertPS.setString(1, username);
            insertPS.setString(2, password);
            insertPS.setString(3, nickname);
            insertPS.setInt(4, Integer.parseInt(ageStr));

            int row = insertPS.executeUpdate();
            if (row > 0) {
                log.info("注册成功!");
                response.sendRedirect("/reg_success.html");
            }

        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        log.info("处理登陆请求");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //判断当前登陆信息是否合法(不为空)
        if (username == null || username.isEmpty() ||
                password == null || password.isEmpty()
        ) {
            try {
                log.error("当前登陆信息为空");
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        try (Connection connection = DBUtil.getConnection()) {
            String querySQL = "SELECT username, `password`, nickname, age " +
                    "FROM user_info " +
                    "WHERE username = ?";
            PreparedStatement queryPS = connection.prepareStatement(querySQL);
            queryPS.setString(1, username);
            ResultSet resultSet = queryPS.executeQuery();
            //如果一个结果都没查到,说明没有该账户,登录信息有误
            if (!resultSet.next()) {
                log.error("账号不存在");
                response.sendRedirect("/login_fail.html");
                return;
            }

            //如果查到结果,就判断登陆密码是否正确
            String rsPassword = resultSet.getString("password");
            if (!rsPassword.equals(password)) {
                log.error("密码错误!");
                response.sendRedirect("/login_fail.html");
                return;
            }

            log.info("登陆成功!");
            response.sendRedirect("/login_success.html");
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request, HttpServletResponse response) {
        try (
                Connection connection = DBUtil.getConnection();
        ) {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>ID</td>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("<td>操作</td>");
            pw.println("</tr>");

            Statement statement = connection.createStatement();
            String sql = "SELECT id, username, `password`, nickname, age " +
                         "FROM user_info";
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                pw.println("<tr>");
                pw.println("<td>" + id + "</td>");
                pw.println("<td>" + resultSet.getString("username") + "</td>");
                pw.println("<td>" + resultSet.getString("password") + "</td>");
                pw.println("<td>" + resultSet.getString("nickname") + "</td>");
                pw.println("<td>" + resultSet.getInt("age") + "</td>");
                pw.println("<td><a href = \"/deleteUser?id=" + id + "\">删除</a></td>");
                pw.println("</tr>");
            }

            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        log.info("执行删除操作");

        //从用户列表那里获取要删除的id
        String id = request.getParameter("id");
        try (Connection connection = DBUtil.getConnection()){
            String deleteSQL = "DELETE FROM user_info WHERE id = ?";
            PreparedStatement deletePS = connection.prepareStatement(deleteSQL);
            deletePS.setInt(1, Integer.parseInt(id));
            deletePS.executeUpdate();
            response.sendRedirect("/userList");
            log.info("删除用户成功");
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }
}














